#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/queue.h"
#include "esp_system.h"
#include "esp_log.h"
#include "esp_err.h"

#include "esp_spi_flash.h"
#include "driver/gpio.h"
#include "lwip/apps/sntp.h"

#include "my_wifi.h"

static const char *TAG = "sntp demo";

#define GPIO_PIN_LED 2
#define GPIO_OUTPUT_PIN (1UL << GPIO_PIN_LED)

void Gpio_Init(void)
{
    gpio_config_t IO_config;

    IO_config.pin_bit_mask = GPIO_OUTPUT_PIN;
    IO_config.mode = GPIO_MODE_OUTPUT;
    IO_config.pull_up_en = GPIO_PULLUP_ENABLE;
    IO_config.pull_down_en = GPIO_PULLDOWN_DISABLE;
    IO_config.intr_type = GPIO_INTR_DISABLE;

    gpio_config(&IO_config);
    gpio_set_level(GPIO_PIN_LED, 1);
}

static void initialize_sntp(void)
{
    ESP_LOGI(TAG, "Initializing SNTP");
    sntp_setoperatingmode(SNTP_OPMODE_POLL);
    sntp_setservername(0, "cn.pool.ntp.org");
    sntp_init();
}

void time_task(void *argv)
{
    time_t now;
    struct tm timeinfo;

    time(&now);
    localtime_r(&now, &timeinfo);

    if (timeinfo.tm_year < (2016 - 1900)) {
        ESP_LOGE(TAG, "Time is not set yet. Connecting to WiFi and getting time over NTP.");
        initialize_sntp();
    }
        
    setenv("TZ", "CST-8", 1);
    tzset();
    while (1)
    {
        time(&now);
        localtime_r(&now, &timeinfo);
            
        printf("%d/%d/%d ", 1900 + timeinfo.tm_year, timeinfo.tm_mon, timeinfo.tm_mday);
        printf("%d:%d:%d\n", timeinfo.tm_hour, timeinfo.tm_min, timeinfo.tm_sec);

        // strftime(strftime_buf, sizeof(strftime_buf), "%c", &timeinfo);
        // ESP_LOGI(TAG, "The current date/time in Shanghai is: %s", strftime_buf);

        vTaskDelay(1000/portTICK_RATE_MS);
    }
}

void app_main()
{   
    ESP_LOGE(TAG,"ESP_LOGE");
    ESP_LOGW(TAG,"ESP_LOGW");
    ESP_LOGI(TAG,"ESP_LOGI");
    ESP_LOGD(TAG,"ESP_LOGD");
    ESP_LOGV(TAG,"ESP_LOGV");

    ESP_ERROR_CHECK(nvs_flash_init());

    ESP_LOGI(TAG,"start Gpio_Init");
    Gpio_Init();

    my_wifi_t wifi_info = {
        .ssid = "HONOR-0415PD",
        .password = "pf0105602"
    };

    ESP_LOGI(TAG,"create time_task");
    xTaskCreate(time_task,"time_task",1024*2,NULL, 22, NULL);

    ESP_LOGI(TAG, "ESP_WIFI_MODE_STA");
    if (wifi_init_sta(&wifi_info)){
        ESP_LOGE(TAG, "CONNECT TO AP FAIL");
    }

    ESP_LOGI(TAG, "Run");
}
